<?php

/**
 * 前台订单处理 类库
 * @copyright Copyright&copy; 2015, 广州六象元一网络科技有限公司
 * @author 王海龙 $
 * @version  $Id: classOrder.php, v 1.0, 2015-01-01 王海龙 $
 * 订单生成/修改/删除等基本操作：
*/
/**
 * addToCart              加入购物车（多个商品）
 * getCartGoods           获取购物车信息（所有商品信息）
 * DelCartGoods           删除购物车商品信息（删除多个）
 * getTotal               获取购物车费用信息（购物车及结算中心同效果）
 * getGift                获取赠品列表
 * getCoupon              获取优惠卷
 * getUserAddrList        获取用户地址
 * orderOutStock          减少订单商品库存
 * getShippingFee         获取配送费用
 * orderDone              提交生成订单
 */


class classOrder {
    public $mem; // memcached
    public $time;//当前时间
    public $goodsListExt = array(); // 购物车扩展商品信息
    public $goodsList = array(); // 购物车商品信息
    public $consignee = array(); // 默认收货人信息
    public $coupon_id;//优惠卷ID
    public $orderInfo = array(
                'pay_id' => 1,
                'shipping_id' => 13,
                'area_id' => 3
            );
    private $c = '';
    private $config = array('512145b6f8ea49a5.m.cnqdalicm9pub001.ocs.aliyuncs.com', 11211, '512145b6f8ea49a5', 'Eggms520');
    // private $config = array('258a7bca241f41a9.m.cnqdalicm9pub001.ocs.aliyuncs.com', 11211, '258a7bca241f41a9', 'Eggms520');
    /**
     * 构造函数
     */
    public function __construct($config = array()) {
        if (empty($config)) {
            $config = $this->config;
        }
        $this->connect($config);
        $this->time = time();
    }

    /**
     * memcached连接
     *
     * @access  private
     * @param   array   配置数组
     * @return  boolean
     */
    private function connect($config = array()) {
        $this->mem = new memcached();
        // 以二进制进行传输，当要进行密码验证时，这个一定要为true
        $this->mem->setOption(Memcached::OPT_BINARY_PROTOCOL, true);
        // 添加服务池
        $this->mem->addServer($config[0], $config[1]);
        // 进行密码验证
        $this->mem->setSaslAuthData($config[2], $config[3]);
        // 取消自动压缩，如果要后面追加数据，不可压缩数据
        $this->mem->setOption(Memcached::OPT_COMPRESSION, false);
    }

    /**
     * 添加商品至购物车
     */
    public function addToCart($goodsList = array()) {
        /* 是否登录用户 */
        $user_id = $_SESSION['user_id'] ? $_SESSION['user_id'] : 0;
        foreach ($goodsList as $key => $value) {
            if (!empty($value['extension_code']) && method_exists($this, 'addToCartExt_' . $value['extension_code'])) {
                // 特殊商品
                $ext = 'addToCartExt_' . $value['extension_code'];
                $result = $this->$ext($value);
                return $result;
            }
            else
            {
                /* 如果为普通商品添加 */
                /* 取得商品信息 */
                $sql = "SELECT g.goods_id, g.goods_name, g.goods_sku,g.market_price, g.promote_price, g.promote_start_date, g.promote_end_date, g.goods_weight, g.is_shipping, g.shop_price ".
                        " FROM egg_goods AS g WHERE g.goods_id = '$value[id]' AND g.is_on_sale = 1 AND g.is_alone_sale = 1 " .
                        " AND g.is_delete = 0";
                $goods = DB()->getRow($sql);

                // 加商品锁
                include_once(ROOT_PATH . 'includes/classLock.php');
                $lock = new classLock;
                if ($lock->lock('addToCartGoods' . $value['id'])) {
                    //判断是否在促销中
                    if ($goods['promote_start_date'] < time() && $goods['promote_end_date'] > time()) {
                        /* 查询闪购信息 */
                        $sql = "SELECT (l.goods_num-l.buy_num) AS goods_num, l.start_time, l.end_time, l.limit_num, l.limit_id ".
                            " FROM egg_limit AS l  WHERE l.start_time <= '" . time() . "' AND l.end_time >= '".time()."' AND l.goods_id = '$goods[goods_id]' ";
                        $data = DB()->getRow($sql);
                        if ($data) {
                            // 查询用户是否已购买过此闪购商品
                            if (!empty($_SESSION['user_id'])) {
                                $sql = "SELECT buy_num FROM egg_user_limit WHERE user_id = $_SESSION[user_id] AND limit_id = $data[limit_id]";
                                $buy_num = DB()->getOne($sql);
                            } else {
                                $buy_num = 0;
                            }
                            // 查询购物车数量
                            $sql = "SELECT sum(goods_number) FROM egg_cart WHERE goods_id = '$goods[goods_id]' AND extension_code = 'limit'";
                            $cartNumber = DB()->getOne($sql);
                            $data['goods_stock'] = $data['goods_num']-$cartNumber;
                            // 判断当前数量是否可以购买
                            $goods['goods_number'] = min(($data['limit_num'] - $buy_num), $data['goods_stock']);
                            if (empty($goods['goods_number']) || $goods['goods_number'] < $value['goods_number']) {
                                $result['error'] = 1;
                                $result['message'] = '此商品已超过限制购买数量！';
                                // 解锁
                                $lock->unlock('addToCartGoods'.$value['id']);
                                return $result;
                            }
                            // 标记为闪购商品
                            $goods['extension_code'] = "limit";
                        } else {
                            $result['error'] = 1;
                            $result['message'] = '此商品不可购买！';
                            // 解锁
                            $lock->unlock('addToCartGoods'.$value['id']);
                            return $result;
                        }
                    } else {
                        // 普通商品
                        if (!empty($value['goods_attr_id'])) {
                            // 含属性商品
                            $goods_attr             = get_goods_attr_info($value['goods_attr_id']); 
                            $goods_attr_sku         = get_goods_attr_sku($value['goods_attr_id']);
                            $goods_attr_id          = implode(',', $value['goods_attr_id']);
                        } else {
                            $goods_attr             = '';
                            $goods_attr_sku         = '';
                            $goods_attr_id          = '';
                        }
                    }

                    if (empty($goods))
                    {
                        $result['error'] = 1;
                        $result['message'] = $GLOBALS['_LANG']['goods_not_exists'];
                        // 解锁
                        $lock->unlock('addToCartGoods'.$value['id']);
                        return $result;
                    }
                    /* 初始化要插入购物车的基本件数据 */
                    $parent = array(
                        'user_id'         => $_SESSION['user_id'],
                        'goods_id'        => $goods['goods_id'],
                        'goods_sku'       => addslashes($goods['goods_sku']),
                        'goods_name'      => addslashes($goods['goods_name']),
                        'market_price'    => $goods['market_price']>0?$goods['market_price']:$goods['shop_price'],
                        'goods_attr'      => !empty($goods_attr) ? $goods_attr : '',
                        'goods_attr_sku'  => !empty($goods_attr_sku) ? $goods_attr_sku : '',
                        'goods_attr_id'   => !empty($goods_attr_id) ? $goods_attr_id : '',
                        'extension_code'  => !empty($goods['extension_code']) ? $goods['extension_code'] : '',
                        'extension_id'    => 0,
                        'parent_id'       => 0,
                        'is_gift'         => 0,
                        'is_real'         => 1,
                        'is_shipping'     => $goods['is_shipping'],
                        'rec_type'        => CART_GENERAL_GOODS,
                        'area_id'         => 3,
                        'add_time'        => time()
                    );

                    /*读取商品库存*/
                    if (!empty($value['goods_attr_id'])) {
                        $sql =  " SELECT goods_number FROM egg_goods_stock".
                                " WHERE goods_sku =".$goods_attr_sku;
                        $preStock = DB()->getOne($sql);
                    }else{
                        $sql =  " SELECT goods_number FROM egg_goods_stock".
                                " WHERE goods_sku =".$goods['goods_sku'];
                        $preStock = DB()->getOne($sql);
                    }
                    /* 检查该商品是否已经存在在购物车中 */
                    $sql = "SELECT goods_number FROM egg_cart WHERE  user_id = $user_id AND goods_id = '$parent[goods_id]' ".
                            " AND parent_id = '$parent[parent_id]' AND goods_attr = '$parent[goods_attr]' " .
                            " AND extension_code = '$parent[extension_code]'";
                    if ($num = DB()->getOne($sql)) {
                        /* 如果存在检查是否超过购买数量 */
                        if (!empty($preStock) && ($num + $value['goods_number']) > $preStock) {
                            $parent['goods_number'] = $preStock;
                        } else {
                            $parent['goods_number'] = $num + $value['goods_number'];
                        }

                        if (!empty($parent['goods_number'])) {
                            /* 查看最新价格 */
                            $parent['goods_price'] = get_final_price($parent['goods_id'], $parent['goods_number'], true, $value['goods_attr_id']);
                            /* 更新购物车数量和价格 */
                            $sql = "UPDATE egg_cart SET goods_number = '$parent[goods_number]'" .
                                " , goods_price = '$parent[goods_price]' ".
                                " WHERE user_id = $user_id AND goods_id = '$parent[goods_id]' ".
                                " AND parent_id = '$parent[parent_id]' AND goods_attr = '$parent[goods_attr]' " .
                                " AND extension_code = '$parent[extension_code]'";
                            DB()->query($sql);
                        } else {
                            $result['error'] = 1;
                            $result['message'] = '此商品已超过限制购买数量！';
                            // 解锁
                            $lock->unlock('addToCartGoods'.$value['id']);
                            return $result;
                        }
                    } else {
                        // 没有，则插入购物车表
                        $parent['goods_price'] = get_final_price($parent['goods_id'], $value['goods_number'], true, $value['goods_attr_id']);
                        $parent['goods_number'] = !empty($preStock)&&$preStock<$value['goods_number']?$preStock:$value['goods_number'];
                        DB()->autoExecute('egg_cart', $parent, 'INSERT');
                    }
                    // 解锁
                    $lock->unlock('addToCartGoods'.$value['id']);
                    
                }else{
                        $result['error'] = 1;
                        $result['message'] = '加入购物车失败';
                }
            }
        }
        $result['error'] = 0;
        $result['message'] = '成功加入购物车';
        
        return $result;
    }

    /**
     * 添加礼包至购物车
     */
    public function addToCartExt_libao($value) {
        // 检查是否有传礼包ID
        if(empty($value['id'])){
            $result['error'] = 1;
            $result['message'] = '参数错误，请重试！';
            return $result;
        }else{
            $parent_id = intval($value['id']);
            $number = intval($value['goods_number']);
        }
        // 检查是否已登录购买
        if(!$_SESSION['user_id']){
            $result['error'] = 1;
            $result['message'] = '请先登录后再购买，谢谢！';
            return $result;
        }
        /* 查询礼包信息 */
        $sql = "SELECT name, original_price, parent_id, extension_code, price, is_sale FROM egg_activity WHERE parent_id = '$parent_id' AND extension_code = 'libao'";
        $info = DB()->getRow($sql);
        if(!$info){
            $result['error'] = 1;
            $result['message'] = '未找到相关礼包信息！';
            return $result;
        }elseif($info['is_sale'] != 1){
            $result['error'] = 1;
            $result['message'] = '当前礼包已停止销售，敬请期待！';
            return $result;
        }
        /* 查询礼包当前可购买数量 */
        // 加锁
        require_once(ROOT_PATH . 'includes/classLock.php');
        $lock = new classLock;
        $lockName = 'lockLibao' . $value['id'];
        if ($lock->lock($lockName)) {
            $area_id = $_SESSION['area_id'] ? $_SESSION['area_id'] : 3;
            $sql = "SELECT valid_number FROM egg_activity_stock WHERE parent_id = '$parent_id' AND area_id = '$area_id'";
            $info['valid_number'] = DB()->getOne($sql);
            if(empty($info['valid_number']) || $info['valid_number'] < $number){
                if(empty($info['valid_number'])){
                    $result['error'] = 1;
                    $result['message'] = '礼包已被抢光！';
                    goto result;
                }else{
                    $result['error'] = 1;
                    $result['message'] = '礼包数量不足，还剩'.$info['valid_number'].'件！';
                    goto result;
                }
            }
            /* 查询购物车是否已存在该礼包 */
            $sql = "SELECT * FROM egg_cart WHERE parent_id = '$info[parent_id]' AND goods_id = 0 AND user_id = '$_SESSION[user_id]'";
            $cartInfo = DB()->getRow($sql);
            if($cartInfo){
                // 更新购物车显示的礼包数量
                $sql = "UPDATE egg_cart SET goods_number = goods_number + $number WHERE goods_id = '0' AND goods_attr_id = '0' AND parent_id = $info[parent_id]";
                DB()->query($sql);
                // 加入成功
                $result['error'] = 0;
                $result['message'] = $result['content'] = '抢购成功，请在两小时内结算，否则视为抢购无效！';
                /* 修改礼包数量 */
                $sql = "UPDATE egg_activity_stock SET valid_number = valid_number - $number WHERE parent_id = '$info[parent_id]' AND area_id = '$area_id'";
                DB()->query($sql);
                goto result;
            } else {
                /* 初始化要插入购物车的数据 */
                $parent = array(
                    'user_id'        => $_SESSION['user_id'],
                    'session_id'     => SESS_ID,
                    'goods_id'       => 0,
                    'goods_sku'      => 0,
                    'goods_name'     => $info['name'],
                    'market_price'   => $info['original_price'],
                    'goods_attr_sku' => 0,
                    'goods_attr_id'  => 0,
                    'extension_code' => $info['extension_code'],
                    'extension_id'   => $info['parent_id'],
                    'is_gift'        => 0,
                    'is_real'        => 0,
                    'is_shipping'    => 0,
                    'area_id'        => $area_id,
                    'add_time'       => time(),
                    'goods_price'    => $info['price'],
                    'goods_number'   => $number,
                    'parent_id'      => $info['parent_id'],
                );
                DB()->autoExecute('egg_cart', $parent, 'INSERT');
                /* 修改礼包数量 */
                $sql = "UPDATE egg_activity_stock SET valid_number = valid_number - $number WHERE parent_id = '$info[parent_id]' AND area_id = '$area_id'";
                DB()->query($sql);
                // 加入成功
                $result['error'] = 0;
                $result['message'] = $result['content'] = '抢购成功，请在两小时内结算，否则视为抢购无效！';
                goto result;
            }
            result:
            // 释放锁
            $lock->unlock($lockName);
            return $result;
        }
    }

    /**
     * 预购商品加入购物车
     */
    public function addToCartExt_yugou($value) {
        // 检查是否有传商品ID
        if(empty($value['id'])){
            $result['error'] = 1;
            $result['message'] = '参数错误，请重试！';
            return $result;
        }else{
            $goods_id = intval($value['id']);
            $extension_code = $value['extension_code'];
            $number = intval($value['goods_number']);
        }
        // 检查是否已登录购买
        if(!$_SESSION['user_id']){
            $result['error'] = 1;
            $result['message'] = '请先登录后再购买，谢谢！';
            return $result;
        }

        /* 查询预购商品信息 */
        $sql = "SELECT po.goods_id, po.goods_sku, po.pre_order_num, po.limit_num, po.buy_num, po.buy_number, po.area_id, po.pre_order_part, po.start_time, po.end_time, po.pre_order_price, gs.goods_number, gs.goods_sku, g.goods_name, g.goods_sku, g.market_price " .
            " FROM egg_pre_order AS po " .
            " LEFT JOIN egg_goods_stock AS gs " .
            " ON gs.goods_sku = po.goods_sku AND gs.area_id = 3 " .
            " LEFT JOIN egg_goods AS g " .
            " ON g.goods_sku = po.goods_sku " .
            " WHERE po.goods_id = '$goods_id' AND g.is_delete = 0 AND po.end_time >= '" . time() . "'";
        $preInfo = DB()->getRow($sql);
        $surplusNum = min(($preInfo['pre_order_num']-$preInfo['buy_num']),$preInfo['goods_number']);//可购买数量
        if (!$preInfo) {
            $result['error'] = 1;
            $result['message'] = '未找到相关商品信息！';
            return $result; 
        } elseif($surplusNum <= 0) { 
            $result['error'] = 1;
            $result['message'] = '当前商品已售罄！';
            return $result;
        }

        /* 查询购物车预购商品是否超过每人可购买数量 */
        $sql = "SELECT c.goods_id, c.goods_sku, c.goods_number, c.extension_code, c.area_id, c.user_id " .
                " FROM egg_cart AS c " .
                " WHERE c.area_id = 3 AND c.user_id = '$_SESSION[user_id]' AND c.extension_code = 'yugou' AND c.goods_id = '$goods_id'";
        $cartInfo = DB()->getRow($sql);
        if (!$cartInfo && $number <= $preInfo['limit_num'] && $number <= $surplusNum) {
            /* 初始化要插入购物车的数据 */
            $parent = array(
                'user_id'        => $_SESSION['user_id'],
                'session_id'     => SESS_ID,
                'goods_id'       => $preInfo['goods_id'],
                'goods_sku'      => $preInfo['goods_sku'],
                'goods_name'     => $preInfo['goods_name'],
                'market_price'   => $preInfo['market_price'],
                'goods_attr_sku' => '',
                'goods_attr_id'  => '',
                'extension_code' => 'yugou',
                'extension_id'   => '',
                'is_gift'        => 0,
                'is_real'        => 1,
                'is_shipping'    => 0,
                'area_id'        => 3,
                'add_time'       => time(),
                'goods_price'    => $preInfo['pre_order_price'],
                'goods_number'   => $number,
                'parent_id'      => 0
            );
            DB()->autoExecute('egg_cart', $parent, 'INSERT');
            /* 更新预购表car_num数据 */
            $sql = "UPDATE egg_pre_order SET car_num = car_num + $number WHERE goods_id = '$goods_id' AND end_time >= '" . time() . "'";
            DB()->query($sql);
            $result['error'] = 0;
            return $result;
        } else if($cartInfo && $cartInfo['goods_number'] + $number <= $preInfo['limit_num'] && $cartInfo['goods_number'] + $number <= $surplusNum) {
            /* 更新购物车预购商品数据 */
            $sql = "UPDATE egg_cart SET goods_number = goods_number + $number WHERE goods_id = '$goods_id' AND goods_sku = $cartInfo[goods_sku] AND extension_code = 'yugou' AND user_id = '$_SESSION[user_id]'";
            DB()->query($sql);
            /* 更新预购表car_num数据 */
            $sql = "UPDATE egg_pre_order SET car_num = car_num + $number WHERE goods_id = '$goods_id' AND end_time >= '" . time() . "'";
            DB()->query($sql);
            $result['error'] = 0;
            $result['message'] = '已成功加入购物车！';
            return $result;
        } else {
            $result['error'] = 1;
            $result['message'] = '每人限购'.$preInfo['limit_num'].'件！还剩'.$surplusNum.'件';
            return $result;
        }
    }

    /**
     * 添加赠品到购物车
     */
    public function addToCartExt_gift($value) {
        $result = array('error' => 0, 'message'=>'','content'=>'');
        // 检查是否有传礼包ID
        if(empty($value['id'])){
            $result['error'] = 1;
            $result['message'] = '参数错误，请重试！';
            return $result;
        }else{
            $parent_id = intval($value['id']);
            $number = intval($value['goods_number']);
        }
        // 检查是否已登录购买
        if(!$_SESSION['user_id']){
            $result['error'] = 1;
            $result['message'] = '请先登录后再购买，谢谢！';
            return $result;
        }
        /* 查询礼包信息 */
        $sql = "SELECT name, original_price, parent_id, extension_code, price, is_sale FROM egg_activity WHERE parent_id = '$parent_id' AND extension_code = 'gift'";
        $info = DB()->getRow($sql);
        if(!$info){
            $result['error'] = 1;
            $result['message'] = '未找到相关赠品信息！请联系客服';
            return $result;
        }elseif($info['is_sale'] != 1){
            $result['error'] = 1;
            $result['message'] = '当前赠品已失效，敬请期待！';
            return $result;
        }
        /* 查询礼包当前可购买数量 */
        // 加锁
        require_once(ROOT_PATH . 'includes/classLock.php');
        $lock = new classLock;
        $lockName = 'lockGift' . $value['id'];
        if ($lock->lock($lockName)) {
            $area_id = $_SESSION['area_id'] ? $_SESSION['area_id'] : 3;
            $sql = "SELECT valid_number FROM egg_activity_stock WHERE parent_id = '$parent_id' AND area_id = '$area_id'";
            $info['valid_number'] = DB()->getOne($sql);
            if(empty($info['valid_number']) || $info['valid_number'] < $number){
                if(empty($info['valid_number'])){
                    $result['error'] = 1;
                    $result['message'] = '赠品已被抢光！';
                    goto result;
                }else{
                    $result['error'] = 1;
                    $result['message'] = '赠品数量不足，还剩'.$info['valid_number'].'件！';
                    goto result;
                }
            }
            /* 查询购物车是否已存在该礼包 */
            $sql = "SELECT * FROM egg_cart WHERE parent_id = '$info[parent_id]' AND goods_id = 0 AND user_id = '$_SESSION[user_id]'";
            $cartInfo = DB()->getRow($sql);
            if($cartInfo){
                // 更新购物车显示的礼包数量
                $sql = "UPDATE egg_cart SET goods_number = goods_number + $number WHERE goods_id = '0' AND goods_attr_id = '0' AND parent_id = $info[parent_id]";
                DB()->query($sql);
                // 加入成功
                $result['error'] = 0;
                $result['message'] = $result['content'] = '抢购成功，请在两小时内结算，否则视为抢购无效！';
                /* 修改礼包数量 */
                $sql = "UPDATE egg_activity_stock SET valid_number = valid_number - $number,cart_number = (cart_number+$number) WHERE parent_id = '$info[parent_id]' AND area_id = '$area_id'";
                DB()->query($sql);
                goto result;
            } else {
                /* 初始化要插入购物车的数据 */
                $parent = array(
                    'user_id'        => $_SESSION['user_id'],
                    'session_id'     => SESS_ID,
                    'goods_id'       => 0,
                    'goods_sku'      => 0,
                    'goods_name'     => $info['name'],
                    'market_price'   => $info['original_price'],
                    'goods_attr_sku' => 0,
                    'goods_attr_id'  => 0,
                    'extension_code' => $info['extension_code'],
                    'extension_id'   => $info['parent_id'],
                    'is_gift'        => 0,
                    'is_real'        => 0,
                    'is_shipping'    => 0,
                    'area_id'        => $area_id,
                    'add_time'       => time(),
                    'goods_price'    => $info['price'],
                    'goods_number'   => $number,
                    'parent_id'      => $info['parent_id'],
                );
                DB()->autoExecute('egg_cart', $parent, 'INSERT');
                /* 修改礼包数量 */
                $sql = "UPDATE egg_activity_stock SET valid_number = valid_number - $number,cart_number = (cart_number+$number) WHERE parent_id = '$info[parent_id]' AND area_id = '$area_id'";
                DB()->query($sql);
                // 加入成功
                $result['error'] = 0;
                $result['message'] = $result['content'] = '恭喜您已经获得赠品，请在两个小时内购买提交！';
                goto result;
            }
            result:
            // 释放锁
            $lock->unlock($lockName);
            return $result;
        }
    }

    /**
     * 获取购物车统计及费用信息
     */
    public function getTotal() {
        $total  = array('real_goods_count' => 0,//商品数量
                        'goods_price'      => 0,//商品总价
                        'goods_price_formated'=>0,
                        'market_price'     => 0,//商品总市场价
                        'market_price_formated'=>0,
                        'shipping_fee'     => 0,//配送费用
                        'shipping_fee_formated'=>0,
                        'integral_money'   => 0,//积分抵消费用
                        'bonus'            => 0,//红包抵消费用
                        'bonus_formated'   => 0,
                        'pay_fee'          => 0,//已经支付金额
                        'goods_weight'     => 0,
                        'is_shipping'      => 0,
                        'goods_count'      => 0,
                        'goods_number_sum'      => 0
                        );
        // 如不存在商品信息，初始化商品信息
        if (empty($this->goodsList)) $this->getCartGoods();
        // 如不存在订单信息，初始化订单信息
        if (empty($this->orderInfo)) $this->getFlowOrderInfo();
        // 统计订单数据
        foreach ($this->goodsList as $key => $value) {
            // 计算商品总价
            $total['goods_price'] += $value['goods_price'] * $value['goods_number'];
            // 计算市场价
            $total['market_price'] += $value['market_price'] * $value['goods_number'];
            // 计算重量
            $total['goods_weight'] += $value['goods_weight'] * $value['goods_number'];
            // 商品种类
            $total['goods_count'] ++;
            // 商品件数
            $total['goods_number_sum'] += $value['goods_number'];
            //预购商品为免邮商品
            if ($value['extension_code'] == 'yugou' || $value['extension_code'] == 'buyone' || !empty($value['is_shipping'])) {
                $total['is_shipping'] = 1;
                /* 如果为一元包邮商品，则自带包邮卷属性 */
                if ($value['extension_code'] == 'buyone') {
                    $total['is_free'] = 1;
                }
            }
            // 是否有缺货商品
            if (!empty($value['is_stockout'])) {
                $total['is_stockout'] = 1;
            }
        }

        /*计算优惠信息*/
        if (!empty($this->coupon_id)) {
            $sql =  " SELECT ct.is_free , ct.discount FROM egg_coupon_type AS ct ".
                    " LEFT JOIN egg_coupon AS c ON c.type_id = ct.type_id ".
                    " WHERE c.coupon_id IN (".$this->coupon_id.") AND c.user_id = '".$_SESSION['user_id']."' AND c.is_use = 0 ";
            $coupon_info = DB()->getAll($sql);
            /*包邮卷优惠*/
            foreach ($coupon_info as $key => $value) {
                if ($value['is_free'] == 1) {
                        $total['is_free'] = 1;
                        $total['shipping_fee'] = 0;
                    }
                if (!empty($value['discount'])&&$value['discount']>0&&$value['discount']<1) {
                    $total['discount']    = $total['goods_price']*(1-$value['discount']);
                }
            }
        }
        $total['is_free'] = !empty($total['is_free'])?$total['is_free']:'0';
        $total['discount'] = !empty($total['discount'])?$total['discount']:'0';

        // 获取邮费信息
        $total['shipping_fee'] = $this->getShippingFee($total['goods_price'], $this->orderInfo['pay_id'], $this->consignee, $total['goods_weight'],$total['is_shipping'],$total['is_free']);
        /* 支付费用 */
        $total['amount'] = $total['goods_price'] + $total['shipping_fee']- $total['discount'];
        // 格式化价格
        $total['shipping_fee_formated']   = price_format($total['shipping_fee'], false);
        $total['goods_price_formated']  = price_format($total['goods_price'], false);
        $total['market_price_formated'] = price_format($total['market_price'], false);
        $total['amount_formated']  = price_format($total['amount'], false);

        $this->total = $total;
        return $total;
    }
    /**
     * 获取当前可领取赠品
     */
    public function getGift($order_amount = 0){
        if (!empty($order_amount)) {
           $where = "AND  a.min_price < '$order_amount' AND a.start_time <= " . $GLOBALS['_CFG']['systemTime'] . " AND a.end_time >= " . $GLOBALS['_CFG']['systemTime'];
        }
        $sql = " SELECT a.* , s.valid_number AS stock FROM egg_activity AS a".
               " LEFT JOIN egg_activity_stock AS s ON a.parent_id = s.parent_id".
               " WHERE a.extension_code = 'gift' AND a.is_sale = 1 ".$where.
               " ORDER BY parent_id ASC ";
        $girtList =  DB()->getAll($sql);
        return $girtList;
    }
    /**
     * 获取快递费用
     */
    public function getShippingFee($goodsAmount, $pay_id = '', $consignee = array(), $goods_weight = 0,$shippingCount = 0,$is_free = 0) {

        $user_id = !empty($_SESSION['user_id'])?$_SESSION['user_id']:0;
        $shipping_fee = 10;
        // 设置10元邮费的省份
        $isBuyTenArea = array(2132,1982,1852,2294,2433,879,1006,860,1257,1119,1361,20,1484,2,1657,38);
        // 设置全国包邮的省份
        $isBuyBaoyouArea = array(2132,1982,1852,2294,2433,879,1006,860,1257,1119,1361,20,1484,2,1657,38,2727,2504,3067,2830,2463,628,499,706,233);
        // 设置个别地区的邮费计算
        $rules = array(
            array(//贵州、四川、陕西：首重8、续重4.5(2727,2504,3067)
                'area'=>array(2727,2504,3067),
                'config'=>array(8,4.5),
            ),
            array(//云南、重庆：首重8、续重5(2830,2463)
                'area'=>array(2830,2463),
                'config'=>array(8,5),
            ),
            array(//新疆：首重16、续重16(3394)
                'area'=>array(3394),
                'config'=>array(16,16),
            ),
            array(//吉林、辽宁、黑龙江：首重8.5、续重5.8(628,499,706)
                'area'=>array(628,499,706),
                'config'=>array(8.5,5.8),
            ),
            array(//山西：首重8.5、续重5.5(233)
                'area'=>array(233),
                'config'=>array(8.5,5.5),
            ),
            array(//内蒙古、青海、甘肃、宁夏：首重12.3、续重9.3(375,3308,3195,3361)
                'area'=>array(375,3308,3195,3361),
                'config'=>array(12.3,9.3),
            ),
            array(//西藏：首重19、续重16(2984)
                'area'=>array(2984),
                'config'=>array(19,16),
            ),
        );

        /* 开始计算邮费 */
        if (($goodsAmount >= 128 || !empty($shippingCount) || $is_free == 1) && in_array($consignee['province'],$isBuyBaoyouArea)) {
            // 如果有包邮商品并且属于包邮地区，运费为0
            $shippingFee = 0;
        } elseif (in_array($consignee['province'],$isBuyTenArea)) {
            // 如果没有包邮商品，并且属于10元运费地区，运费为10
            $shippingFee = 10;
            // 参与全免计划的成员免邮
            $sql = "SELECT COUNT(*) FROM egg_user_freeplan WHERE user_id = $user_id AND addtime < 1414230376 AND exam_year != '2015年' AND exam_year != '2015'";
            if($user_id && DB()->getOne($sql)){
                $shippingFee = 0;
            }
        } else {
            /*非包邮地区邮费计算*/
            foreach($rules AS $key => $rule){
                if(in_array($consignee['province'],$rule['area'])){
                    $shippingFee = $rule['config'][0];
                    if($goods_weight > 1){
                        $goods_weight = ceil($goods_weight) - 1;
                        $shippingFee += ($rule['config'][1] * $goods_weight);
                    }
                }
            }
            /*非包邮地区优惠卷减邮费10块*/
            if ($is_free == 1) {
                $shippingFee = $shippingFee - 10;
                if ($shippingFee < 0) {
                    $shippingFee = 0;
                }
            }
        }

        // 到付手续费
        if($pay_id == 3 && $goodsAmount <= 168){
            $shippingFee += 5;
        }
        return $shippingFee;
    }

    /**
     * 获取购物车商品
     * @param   $recId   array   指定购物商品
     */
    public function getCartGoods($recId = array()) {
        /* 是否登录用户 */
        $user_id = $_SESSION['user_id'] ? $_SESSION['user_id'] : 0;
        /* SQL查询条件 */
        $where = " WHERE (user_id = $user_id)";

        /* 是否获取指定购物车商品 */
        if (!empty($recId)) {
            $where .= " AND c.rec_id IN (" . implode(',', $recId) . ")";
        }
        /* 生成MYSQL语句 */
        $sql =  " SELECT g.goods_id, g.goods_thumb, g.goods_weight, g.preferential_price, g.seller_note, g.promote_start_date, g.promote_price, g.promote_end_date, c.rec_id, c.user_id, c.goods_name, c.goods_sku, c.goods_attr_id, c.goods_attr_sku, c.goods_number, c.area_id, c.market_price, c.goods_price, c.goods_attr, c.is_real, c.extension_code, c.parent_id, c.is_gift, c.is_shipping,c.goods_price * c.goods_number AS subtotal " .
                " FROM egg_cart c " .
                " LEFT JOIN egg_goods g ON(g.goods_id = c.goods_id) " . $where;
        /* 获取购物车所有商品信息 */
        $this->goodsList = DB()->getAll($sql);
        if (empty($this->goodsList)) {
            return false;
        }
        /* 格式化商品信息 */
        foreach ($this->goodsList as $key => $value)
        {
            /* 如果不存在此商品信息 */
            if (empty($value['extension_code']) && empty($value['goods_id'])) {
                $sql = "DELETE FROM egg_cart WHERE rec_id = $value[rec_id]";
                DB()->query($sql);
                $value = false;
            }
            /* 记录扩展信息并分类 */
            if (!empty($value['extension_code'])) {
                $value = $this->getCartGoodsExt($value);
                $this->goodsListExt[$value['extension_code']][] = $value;
            }
            /*普通商品查询库存*/
            if (empty($value['extension_code']) && !empty($value['goods_id'])) {
                // 获取库存标识
                $sku = !empty($value['goods_attr_sku'])?$value['goods_attr_sku']:$value['goods_sku'];
                // 获取库存
                $value['goods_stock'] = $GLOBALS['virtualStock']->selectStock($sku);
                // 是否缺货
                $value['is_stockout'] = $value['goods_stock'] < $value['goods_number'] ? 1 : 0;
                // 是否可购买
                $value['is_buy']      = $value['goods_stock'] < $value['goods_number'] ? 0 : 1;
            }
            // 计算小计
            $value['formated_subtotal'] = price_format($value['goods_number'] * $value['goods_price'], false);
            // 计算已优惠价格
            $value['preferential'] = ($value['market_price']-$value['goods_price'])*$value['goods_number'];
            if (!empty($value)) {
                $this->goodsList[$key] = $value;
            } else {
                unset($this->goodsList[$key]);
            }
            if ($recId) {
                $recArr[] = $value['rec_id'];
            }
        }
        /* 检查查询结果与条件的一致 */
        if ($recId) {
            if (!empty(array_diff($recArr,$recId))) {
                return false;
            }
        }
        return $this->goodsList;
    }

    /**
     * 获取扩展商品信息
     * @param   $value   array   指定商品信息
     */
    public function getCartGoodsExt($value = array()) {
        $ext = 'getCartGoodsExt_' . $value['extension_code'];
        return $this->$ext($value);
    }

    /**
     * 获取礼包商品信息
     * @param   $value   array   指定商品信息
     */
    public function getCartGoodsExt_libao($value = array()) {
        if ($value['goods_id'] == 0) {
            $sql = "SELECT img, is_delete, is_sale FROM egg_activity WHERE parent_id = $value[parent_id]";
            $data = DB()->getRow($sql);
            /* 是否存在此礼包 */
            if ($data) {
                $value['goods_thumb'] = $data['img'];
                if ($data['is_delete'] == 0 && $data['is_sale'] == 1) {
                    $value['is_buy'] = 1;
                } else {
                    $value['is_buy'] = 0;
                }
                return $value;
            }
            // 如果不存在则返回FALSE
            else {
                return false;
            }
        }
        return false;
    }

    /**
     * 获取闪购商品信息
     * @param   $value   array   指定商品信息
     */
    public function getCartGoodsExt_limit($value = array()) {
        /* 判断商品是否有效 */
        if($value['promote_start_date'] < time() && time() < $value['promote_end_date']){
            /* 查询闪购信息 */
            $sql = "SELECT (l.goods_num-l.buy_num) AS goods_num, l.start_time, l.end_time, l.limit_num, l.limit_id FROM egg_limit AS l  WHERE l.start_time <= '" . time() . "' AND l.end_time >= '".time()."' AND l.goods_id = '$value[goods_id]' ";
            $data = DB()->getRow($sql);

            if ($data) {
                // 查询用户是否已购买过此闪购商品
                if (!empty($_SESSION['user_id'])) {
                    $sql = "SELECT buy_num FROM egg_user_limit WHERE user_id = $_SESSION[user_id] AND limit_id = $data[limit_id]";
                    $buy_num = DB()->getOne($sql);
                } else {
                    $buy_num = 0;
                }
                // 判断当前数量是否可以购买
                if ($data['limit_num'] >= $buy_num + $value['goods_number'] && $value['goods_number'] <= $data['goods_num']) {
                    // 是否缺货
                    $value['is_stockout'] = 0;
                    $value['is_buy'] = 1;
                    $value['goods_stock'] = min($data['limit_num'],$data['goods_num']);

                } else {
                    // 是否缺货
                    $value['is_stockout'] = 1;
                    $value['is_buy'] = 0;
                    $value['goods_stock'] = min($data['limit_num'],$data['goods_num']);
                }
            }
            // 如果不存在则删除购物车里面的闪购商品
            else {
                $sql = "DELETE FROM egg_cart WHERE rec_id = $value[rec_id]";
                DB()->query($sql);
                return false;
            }
        } else {
            $value['is_buy'] = 0;
            $value['goods_stock'] = 0;
        }
        return $value;
    }


    /**
     * 获取预购商品信息
     * @param   $value   array   指定商品信息
     */
    public function getCartGoodsExt_yugou($value = array()) {
        /* 查询预购商品信息 */
        $sql = " SELECT po.pre_order_num, po.limit_num, po.buy_num, po.buy_number, po.area_id, po.pre_order_part, po.start_time, po.end_time, po.pre_order_price " . 
            " FROM egg_pre_order AS po WHERE po.goods_id = '$value[goods_id]' AND po.end_time >= '" . time() . "'";
        $data = DB()->getRow($sql); 
        if($data){
            /* 判断是不是在活动时间内：是可勾选，不是则不可勾选 */
            if($data['start_time'] <= $this->time && $this->time <= $data['end_time']){
                $value['is_buy'] = 1;
            }else{
                $value['is_buy'] = 0;
            }
            /* 判断购物车商品数量是否超过每人限定数量 */
            if($value['goods_number'] > $data['limit_num']){
                $value['is_stockout'] = 1;
            }else{
                $value['is_stockout'] = 0;
            }
        }
        /*读取商品库存*/
        require_once(ROOT_PATH . 'includes/classStock.php');
        $stock = new classStock();
        $preStock = $stock->selectStock($value['goods_sku']);
        !empty($data['pre_order_num']) || $data['pre_order_num'] = 1;
        /* 预购商品剩余数量（根据公式得出） */
        $surplusNum =  intval((min(($data['pre_order_num']-$data['buy_num']),$preStock)/$data['pre_order_num'])*$data['buy_number']);
        /* 可购买数量（根据公式得出） */
        $canBuyNum = min(($data['pre_order_num']-$data['buy_num']),$preStock);

        /* 判断是否大于剩余数量或者大于可购买数量，大于则不可提交订单 */
        if($value['goods_number'] > $canBuyNum || $value['goods_number'] > $surplusNum){
            $value['is_stockout'] = 1;
        }else{
            $value['is_stockout'] = 0;
        }
        return $value;
    }

    /**
     * 获取购物车赠品信息
     */
    public function getCartGoodsExt_gift($value = array()) {
        if ($value['goods_id'] == 0) {
            $sql = "SELECT img, is_delete, is_sale FROM egg_activity WHERE parent_id = $value[parent_id]";
            $data = DB()->getRow($sql);
            /* 是否存在此礼包 */
            if ($data) {
                if (empty($data['img'])) {
                    $sql = "SELECT goods_id FROM egg_activity_goods WHERE parent_id = '$value[parent_id]'";;
                    $goods_id = DB()->getOne($sql);
                    $sql = "SELECT goods_thumb FROM egg_goods WHERE goods_id = '$goods_id'";;
                    $value['goods_thumb'] = DB()->getOne($sql);
                } else {
                    $value['goods_thumb'] = $data['img'];
                }
                if ($data['is_delete'] == 0 && $data['is_sale'] == 1) {
                    $value['is_buy'] = 1;
                } else {
                    $value['is_buy'] = 0;
                }
                return $value;
            }
            // 如果不存在则返回FALSE
            else {
                return false;
            }
        }
        return false;
    }

    /**
     * 获取购物车一元包邮商品信息
     */
    public function getCartGoodsExt_buyone($value = array()) {
        if ($value['goods_id'] == 0) {
            $sql = "SELECT img, is_delete, is_sale FROM egg_activity WHERE parent_id = $value[parent_id]";
            $data = DB()->getRow($sql);
            /* 是否存在此商品信息 */
            if ($data) {
                if (empty($data['img'])) {
                    $sql = "SELECT goods_id FROM egg_activity_goods WHERE parent_id = '$value[parent_id]'";;
                    $goods_id = DB()->getOne($sql);
                    $sql = "SELECT goods_thumb FROM egg_goods WHERE goods_id = '$goods_id'";;
                    $value['goods_thumb'] = DB()->getOne($sql);
                } else {
                    $value['goods_thumb'] = $data['img'];
                }
                if ($data['is_delete'] == 0 && $data['is_sale'] == 1) {
                    $value['is_buy'] = 1;
                } else {
                    $value['is_buy'] = 0;
                }
                return $value;
            }
            // 如果不存在则返回FALSE
            else {
                return false;
            }
        }
        return false;
    }

    /**
     * 删除购物车信息
     * @param   $rec_id   array   指定要删除的购物车信息
     */
    public function delCartGoods($rec_id = array()) {
        // 将要删除的键值转为数组
        if (!empty($rec_id) && !is_array($rec_id)) {
            $rec_id = array($rec_id);
        }
        /* 是否登录用户 */
        $user_id = $_SESSION['user_id'] ? $_SESSION['user_id'] : 0;
        // 查询相关购物车信息
        $sql = "SELECT parent_id, extension_code, rec_id, goods_id, goods_number FROM egg_cart WHERE rec_id IN (" . implode(',', $rec_id) . ") AND (session_id = '" . SESS_ID . "' OR user_id = $user_id)";
        $goodsList = DB()->getAll($sql);

        if (!empty($goodsList)) {
            // 循环删除购物信息
            foreach ($goodsList as $key => $value) {
                if (empty($value['extension_code'])) {
                    // 普通商品执行删除
                    $sql = "DELETE FROM egg_cart WHERE rec_id = '$value[rec_id]'";
                    DB()->query($sql);
                } else {
                    // 特殊商品执行特殊删除
                    $ext = 'delCartGoodsExt_' . $value['extension_code'];
                    $this->$ext($value);
                }
            }
            return true;
        }
        return false;
    }

    /**
     * 删除购物车礼包信息
     * @param   $value   array   指定商品信息
     */
    public function delCartGoodsExt_libao($value = array()) {
        if (!empty($value['parent_id'])) {
            // 添加礼包锁
            require_once(ROOT_PATH . 'includes/classLock.php');
            $lock = new classLock;
            $lockName = 'lockLibao' . $value['parent_id'];
            // 如果加锁成功
            if ($lock->lock($lockName)) {
                /* 删除用户购物车礼包信息 */
                $sql = "DELETE FROM egg_cart WHERE parent_id = '$value[parent_id]' AND user_id = '$_SESSION[user_id]'";
                DB()->query($sql);
                /* 更新礼包数量 */
                $sql = "UPDATE egg_activity_stock SET valid_number = valid_number + $value[goods_number] WHERE parent_id = '$value[parent_id]' AND area_id = '3'";
                DB()->query($sql);
                // 解礼包锁
                $lock->unlock($lockName);
                return true;
            }
        }
        return false;
    }

    /**
     * 删除购物车闪购信息
     * @param   $value   array   指定商品信息
     */
    public function delCartGoodsExt_limit($value = array()) {
        // 闪购商品执行删除
        $sql = "DELETE FROM egg_cart WHERE rec_id = '$value[rec_id]'";
        DB()->query($sql);
        return true;
    }

    /**
     * 删除购物车预购商品信息
     * @param   $value   array   指定商品信息
     */
    public function delCartGoodsExt_yugou($value = array()) {
        /* 预购商品执行删除 */
        $sql = "DELETE FROM egg_cart WHERE rec_id = '$value[rec_id]'";
        DB()->query($sql);

        /* 更新预购表car_num */
        $sql = "UPDATE egg_pre_order SET car_num = car_num - '$value[goods_number]' WHERE goods_id = '$value[goods_id]' AND end_time >= '" . time() . "'";
        DB()->query($sql);
        return true;
    }

    /**
     * 删除购物车赠品商品信息
     * @param   $value   array   指定商品信息
     */
    public function delCartGoodsExt_gift($value = array()) {
        if (!empty($value['parent_id'])) {
            // 添加礼包锁
            require_once(ROOT_PATH . 'includes/classLock.php');
            $lock = new classLock;
            $lockName = 'lockGift' . $value['parent_id'];
            // 如果加锁成功
            if ($lock->lock($lockName)) {
                /* 删除用户购物车礼包信息 */
                $sql = "DELETE FROM egg_cart WHERE parent_id = '$value[parent_id]' AND user_id = '$_SESSION[user_id]'";
                DB()->query($sql);
                /* 更新礼包数量 */
                $sql = "UPDATE egg_activity_stock SET valid_number = valid_number + $value[goods_number] ,cart_number = cart_number - $value[goods_number] WHERE parent_id = '$value[parent_id]' AND area_id = '3'";
                DB()->query($sql);
                // 解礼包锁
                $lock->unlock($lockName);
                return true;
            }
        }
        return true;
    }

    /**
     * 删除购物车一元包邮商品信息
     * @param   $value   array   指定商品信息
     */
    public function delCartGoodsExt_buyone($value = array()) {
        if (!empty($value['parent_id'])) {
            /* 删除用户购物车商品信息 */
            $sql = "DELETE FROM egg_cart WHERE parent_id = '$value[parent_id]' AND user_id = '$_SESSION[user_id]'";
            DB()->query($sql);
            /* 更新一元包邮数量 */
            $sql = "UPDATE egg_activity_stock SET valid_number = valid_number + $value[goods_number] ,cart_number = cart_number - $value[goods_number] WHERE parent_id = '$value[parent_id]' AND area_id = '3'";
            DB()->query($sql);
        }
        return true;
    }

    /**
     * 获取用户购物地址
     */
    public function getUserAddrList($addrId = 0) {
        if (!empty($_SESSION['user_id'])) {
            // 已登录
            $where = " ua.user_id = '$_SESSION[user_id]' ";
            if ($addrId) {
                $where .= " AND ua.address_id = '$addrId'";
            }
            // 获取所有地址
            $sql = "SELECT * FROM egg_user_address ua WHERE $where ORDER BY ua.address_id DESC LIMIT 10";
            $addrList = DB()->getAll($sql);
            if ($addrList) {
                // 获取默认地址
                $sql = "SELECT address_id FROM egg_users WHERE user_id = '$_SESSION[user_id]'";
                $address_id = DB()->getOne($sql);
                foreach ($addrList as $key => $value) {
                    // 格式化地址
                    $addrList[$key]['area_address'] = selectaddress($value['province']) . ' ' . selectaddress($value['city']) . ' ' . selectaddress($value['district']);
                    if (!empty($address_id) && $value['address_id'] == $address_id) {
                        // 设置默认地址
                        $this->consignee = $addrList[$key];
                        $addrList[$key]['isDefault'] = 1;
                    }
                }
                if (empty($this->consignee)) {
                    $this->consignee = $addrList[0];
                    $addrList[0]['isDefault'] = 1;
                }
                return $addrList;
            }
            // 没有地址返回false
            return false;
        } else {
            return false;
        }
    }

    /*减少订单库存*/
    public function orderOutStock($orderId, $orderGoods) {
        if (empty($orderGoods) && !empty($orderId)) {
            require_once(ROOT_PATH . 'includes/classStock.php');
            $stock = new classStock();
            /* 查询订单商品信息 */
            $sql = "SELECT * FROM egg_order_goods WHERE order_id = '$orderId'";
            $order_goods = DB()->getAll($sql);
            foreach($order_goods AS $key => $value){
                if (!empty($value['extension_code'])) {
                    /*特殊处理*/
                    $ext = 'outStockExt_' . $value['extension_code'];
                    $stock->$ext($value);
                }
                else{
                    $sku = !empty($value['goods_attr_sku'])?$value['goods_attr_sku']:$value['goods_sku'];
                    $stock->outStockDb($sku,$value['goods_number']);
                }
            }
        } elseif (!empty($orderGoods) && is_array($orderGoods)) {
            require_once(ROOT_PATH . 'includes/classStock.php');
            $stock = new classStock();
            foreach ($orderGoods as $key => $value) {
                if (!empty($value['extension_code'])) {
                    /*特殊处理*/
                    $ext = 'outStockExt_' . $value['extension_code'];
                    $stock->$ext($value);
                }
                else{
                    $sku = !empty($value['goods_attr_sku'])?$value['goods_attr_sku']:$value['goods_sku'];
                    $stock->outStockDb($sku,$value['goods_number']);
                }
            }
        }
    }

    /*取消订单增加库存*/
    public function orderAddStock($orderId) {
        require_once(ROOT_PATH . 'includes/classStock.php');
        $stock = new classStock();
        /* 查询订单商品信息 */
        $sql = "SELECT * FROM egg_order_goods WHERE order_id = '$orderId'";
        $order_goods = DB()->getAll($sql);
        foreach($order_goods AS $key => $value){
            if (!empty($value['extension_code'])) {
                /*特殊处理*/
               $ext = 'addStockExt_' . $value['extension_code'];
               $stock->$ext($value);
            }
            else {
                $sku = !empty($value['goods_attr_sku'])?$value['goods_attr_sku']:$value['goods_sku'];
                $stock->addStockDb($sku,$value['goods_number']);
                $stock->addStock($sku,$value['goods_number']);
            }
        }
    }

    /**
     * 生成订单
     * @param   $orderInfo   array   订单信息
     * @param   $orderGoods  array   商品信息
     * @param   $isDone      bool    是否直接完成订单
     */
    public function orderDone($orderInfo = array(), $goodsList = array(), $isDone = false) {
        include_once(ROOT_PATH . 'includes/lib_clips.php');
        include_once(ROOT_PATH . 'includes/lib_payment.php');
        if (empty($orderInfo)) $orderInfo = $this->orderInfo;
        if (empty($goodsList)) $goodsList = $this->goodsList;
        if (!empty($GLOBALS['_CFG']['orderToQueue']) && empty($isDone)) {
            /* 将订单加入队列 */
            // 加载队列类库
            require_once(ROOT_PATH . 'includes/classQueue.php');
            $cQueue = new classQueue;
            // 加载计数器类库
            require_once(ROOT_PATH . 'includes/classCounter.php');
            $c = new classCounter;
            $cName = 'orderDoneSum';
            $c->addCounter($cName, 0);
            if ($num = $c->inCounter($cName)) {
                // 如果取号成功
                // 队名的规则为：当前号除orderQueueMax取倍数，即每orderQueueMax单为一条队
                $qName = 'orderDoneQueue' . intval($num/$GLOBALS['_CFG']['orderQueueMax']);
                $data['orderInfo'] = $orderInfo;
                $data['goodsList'] = $goodsList;
                // 加载库存处理类
                require_once(ROOT_PATH . 'includes/classStock.php');
                $cStock = new classStock;
                foreach ($data['goodsList'] as $key => $value) {
                    /* 队列先处理闪购信息 */
                    if ($value['extension_code'] == 'limit') {
                        $cStock->outStockExt_limit($value);
                        $data['goodsList'][$key]['processed'] = 1;
                    }
                    /* 队列先处理预购信息 */
                    if ($value['extension_code'] == 'yugou') {
                        $cStock->outStockExt_yugou($value);
                        $data['goodsList'][$key]['processed'] = 1;
                    }
                    /* 删除购物车数据 */
                    if (!empty($value['rec_id'])) {
                        $sql = "DELETE FROM egg_cart WHERE rec_id = '$value[rec_id]'";
                        DB()->query($sql);
                    }
                }
                if ($cQueue->append($qName, $data)) {
                    $result['error']              = 0;
                    $result['message']            = '您的订单已成功提交，已购买成功，但由于太多人买单，订单正在排队，请5分钟后再到"个人中心->个人订单"进行查看并付款！';
                    return $result;
                } else {
                    // 添加失败
                    return false;
                }
            } else {
                // 取号失败
                return false;
            }
        } else {
            // 直接生成订单
            /* 插入订单表 */
            $error_no = 0;
            do
            {
                $orderInfo['order_sn'] = get_order_sn(); //获取新订单号

                /* 把订单信息写入order_info表 */
                DB()->autoExecute('egg_order_info', $orderInfo, 'INSERT', '', 'SILENT'); 

                $error_no = DB()->errno();

                if ($error_no > 0 && $error_no != 1062)
                {
                    $result['error']              = 601;
                    $result['message']            = DB()->errorMsg();
                    return $result;
                }
            }
            while ($error_no == 1062); //如果是订单号重复则重新提交数据
            $new_order_id = DB()->insert_id(); // 获取新插入的订单ID
            $orderInfo['order_id'] = $new_order_id;
            /* 插入订单商品 */
            /* 转移并清空购物车 */
            foreach ($goodsList as $key => $value) {
                /* 插入商品至购物车 */
                $sql = "INSERT INTO egg_order_goods (order_id, goods_id, goods_name, goods_sku, goods_number, market_price, goods_price, goods_attr, goods_attr_sku, is_real, extension_code, parent_id, is_gift, goods_attr_id,  user_name, add_time) ".
                    "VALUES('$orderInfo[order_id]', '$value[goods_id]', '$value[goods_name]', '$value[goods_sku]', '$value[goods_number]', '$value[market_price]', '$value[goods_price]', '$value[goods_attr]', '$value[goods_attr_sku]', '$value[is_real]', '$value[extension_code]', '$value[parent_id]', '$value[is_gift]', '$value[goods_attr_id]',  '$_SESSION[user_name]', '$orderInfo[add_time]')";
                DB()->query($sql);
                /* 删除购物车数据 */
                if (!empty($value['rec_id'])) {
                    $sql = "DELETE FROM egg_cart WHERE rec_id = '$value[rec_id]'";
                    DB()->query($sql);
                }
            }
            /* 插入支付日志 */
            $orderInfo['log_id'] = insert_pay_log($orderInfo['order_id'], $orderInfo['order_amount'], PAY_ORDER);
            /* 发放全免计划奖金 */
            order_receive_freeplan($orderInfo);

            /* 下单时减少库存 */
            $this->orderOutStock($orderInfo['order_id'], $goodsList);
            /* 清除缓存，否则买了商品，但是前台页面读取缓存，商品数量不减少 */
            clear_all_files();
            $this->orderInfo = $orderInfo;

            /* 取得支付信息，生成支付代码 */
            if ($orderInfo['order_amount'] > 0 && $orderInfo['pay_id'] != 3)
            {
                $payment = payment_info($orderInfo['pay_id']);
                if($payment['pay_code']){
                    include_once('includes/modules/payment/' . $payment['pay_code'] . '.php');
                    $pay_obj    = new $payment['pay_code'];
                    $pay_online = $pay_obj->get_code($orderInfo, unserialize_config($payment['pay_config']), 1);//支付地址
                    $result['error']              = 0;
                    $result['message']            = '订单提交成功';
                    $result['content']['payUrl']  = $pay_online;
                    $result['content']['orderId'] = $orderInfo['order_id'];
                    $result['content']['payId']   = $orderInfo['pay_id'];
                    return $result;
                }
            } else{
                    $result['error']              = 0;
                    $result['message']            = '订单提交成功';
                    $result['content']['orderId'] = $orderInfo['order_id'];
                    $result['content']['payId']   = $orderInfo['pay_id'];
                    return $result;
            }
            return false;
        }
    }
   /**
     * 获取优惠卷信息
     * @param   $money   int   订单金额
     * @return  coupon
     */
    public function getCoupon($money=0){
        $user_id = $_SESSION['user_id'] ? $_SESSION['user_id'] : 0;
        $time = time();
        $sql =  " SELECT c.* , ct.* FROM egg_coupon AS c".
                " LEFT JOIN egg_coupon_type AS ct ON c.type_id = ct.type_id ".
                " WHERE use_price <= $money AND user_id = '$user_id' AND is_use = '0' AND start_time < $time AND end_time > $time ".
                " GROUP BY ct.type_name";
        $coupon = DB()->getAll($sql);
        foreach ($coupon as $key => $value) {
            $coupon[$key]['start_time_format'] = date('Y-m-d',$coupon[$key]['start_time']);
            $coupon[$key]['end_time_format']   = date('Y-m-d',$coupon[$key]['end_time']);
        }
        return $coupon;
    }
   /**
     * 标记优惠卷已使用
     * @param   $coupon_id      优惠卷ID
     * @return  boll
     */
    public function useCoupon($coupon_id){
        if (!empty($coupon_id)) {
            $sql =  "UPDATE egg_coupon SET is_use = 1 WHERE coupon_id IN($coupon_id)" ;
            DB()->query($sql);
            return true;
        } else {
            return false;
        }
    }








}
